﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.EntityClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace WMS
{
	public partial class WarehouseForm : Form
	{
		int _currentId;
		string _currentCode;

		public WarehouseForm()
		{			
			InitializeComponent();

			DALHelper.FetchCollection(_shelfTypes, null, null, new SortExpression(ShelfTypeFields.Order | SortOperator.Ascending));

			Business.GetPrimaryStores(_parentStores);

			Business.RefreshStoreOccupancyRate();

			var dataForm = new DataMngrFormBase<StoreEntity>(_stores, dataGridView1, bindingSource1, SaveBtn, SaveResult, DeleteResult);
			dataForm.SetMNInfo(typeof(StorekeeperEntity), AllList, AssignedList, UserFields.Id, UserFields.Name, StorekeeperFields.KeeperId, StorekeeperFields.StoreId);
			dataForm.SetMNAssociationButtons(AssignSelectedBtn, AssignAllBtn, UnAssignSelectedBtn, UnAssignAllBtn, SaveDetailsBtn);
			dataForm.SetNumericFields(new List<int> { 3, 4 });
			dataForm.SetMandatoryFields(new List<int>() { 0, 1 });
			dataForm.MNSaved += new DataMngrFormBase<StoreEntity>.RaiseMNSaved(dataForm_MNSaved);
			dataForm.SelectionChanged += new DataMngrFormBase<StoreEntity>.RaiseSelectionChanged(dataForm_SelectionChanged);
			dataForm.AfterSave += new DataMngrFormBase<StoreEntity>.RaiseAfterSave(dataForm_AfterSave);
			dataForm.BeforeSave += new DataMngrFormBase<StoreEntity>.RaiseBeforeSave(dataForm_BeforeSave);
			var uniqueFields = new Dictionary<int, EntityField2>();
			uniqueFields.Add(0, StoreFields.Code);
			uniqueFields.Add(1, StoreFields.Name);
			dataForm.SetUniqueFields(uniqueFields, StoreFields.Id);

			dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
		}

		void dataForm_BeforeSave(IEntityCollection2 collectionToBeSaved)
		{
			foreach(StoreEntity store in collectionToBeSaved)
			{
				if (!store.IsPrimary.HasValue || store.IsPrimary.Value)//if(!(store.IsPrimary.HasValue && !store.IsPrimary.Value))
				{
					store.ParentStoreId = null;
				}
			}
		}

		void dataForm_AfterSave()
		{
			Business.CleanStoreParentRelations();
			Business.GetPrimaryStores(_parentStores);
			ParentStoresBS.ResetBindings(false);
			
		}

		void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			//if (e.ColumnIndex == 5)
			//{
			//    ((DataGridViewCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).ReadOnly = (_currentId == 0) ? false : true;
			//}

			//else if (e.ColumnIndex == 6)
			if (e.ColumnIndex == 6)
			{
				var isPrimaryValue = dataGridView1.Rows[e.RowIndex].Cells[5].Value;
				bool isPrimary = (isPrimaryValue == null) ? false : bool.Parse(isPrimaryValue.ToString());

				((DataGridViewCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).ReadOnly = (isPrimary) ? true : false;
			}
		}

		void dataForm_MNSaved(int selectedId)
		{
			MessageBox.Show("تم الحفظ بنجاح.");
		}
		
		void dataForm_SelectionChanged(int selectedRowIndex)
		{
			//_currentId = int.Parse(dataGridView1.Rows[selectedRowIndex].Cells[dataGridView1.ColumnCount - 1].Value.ToString());
			var selectedValue = dataGridView1.Rows[selectedRowIndex].Cells[dataGridView1.ColumnCount - 1].Value;
			_currentId = (selectedValue == null) ? 0 : int.Parse(selectedValue.ToString());

			var selectedCode = dataGridView1.Rows[selectedRowIndex].Cells[codeDataGridViewTextBoxColumn.Index].Value;
			_currentCode = (selectedCode == null) ? string.Empty : selectedCode.ToString();

			if(_currentId == 0)
				((DataGridViewCell)dataGridView1.Rows[selectedRowIndex].Cells[5]).Value = true;

			LoadShelves();
		}

		DataMngrFormBase<ShelfEntity> _shelvesForm;
		private void LoadShelves()
		{
			if (_shelvesForm != null)
			{
				_shelvesForm.Dispose();
				_shelvesForm = null;
			}
			_shelvesForm = new DataMngrFormBase<ShelfEntity>(_shelves, dataGridView2, bindingSource2, SaveShelvesBtn, _savedShelvesCountLbl, _deletedShelvesCountLbl, new RelationPredicateBucket(ShelfFields.StoreId == _currentId));
			_shelvesForm.SetNumericFields(new List<int> { 4 });
			_shelvesForm.SetMandatoryFields(new List<int>() { 0, 1, 2});
			_shelvesForm.BeforeSave += new DataMngrFormBase<ShelfEntity>.RaiseBeforeSave(_shelvesForm_BeforeSave);

			var uniqueFields = new Dictionary<int, EntityField2>();
			uniqueFields.Add(0, ShelfFields.Code);
			_shelvesForm.SetUniqueFields(uniqueFields, ShelfFields.Id);

			if (_currentId == 0)
			{
				dataGridView2.Enabled = false;
				SaveShelvesBtn.Enabled = false;				
			}
			else
			{
				dataGridView2.Enabled = true;
				SaveShelvesBtn.Enabled = true;
			}

			//if(dataGridView1.SelectedRows.Count > 0)
			//    ((DataGridViewCell)dataGridView1.SelectedRows[0].Cells[5]).ReadOnly = (_currentId == 0)?false:true;
		}

		void _shelvesForm_BeforeSave(IEntityCollection2 collectionToBeSaved)
		{
			foreach (ShelfEntity shelf in collectionToBeSaved)
			{
				shelf.StoreId = _currentId;
				shelf.StoreCode = _currentCode;
			}
		}

        private void btnSearchStore_Click(object sender, EventArgs e)
        {
            string name;
            var searchForm = new fromGeneralEntityPicker("Store");
            if (searchForm.ShowDialog() == DialogResult.OK)
            
                 name = searchForm.SelectedItemCode;

        }
	}
}
